package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ReadBehaviorDto;
import com.heima.behavior.pojos.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存阅读行为
     * 1. 阅读行为不需要回显和查询, 所以不需要保存到redis, 直接保存到数据库即可
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //1.参数校验
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取登录用户id
        ApUser user = ApThreadLocalUtil.getUser();
        if (user == null) {
            //表示未登录
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行此操作
        if (user.getId() == 0) {
            return ResponseResult.okResult(405, "游客身份不能进行此操作");
        }
        //2.查询用户阅读行为
        Criteria criteria=new Criteria().orOperator(Criteria.where("userId").is(user.getId()),Criteria.where("equipmentId").is(dto.getEquipmentId())).andOperator(Criteria.where("articleId").is(dto.getArticleId()));
        ApReadBehavior apReadBehavior = mongoTemplate.findOne(Query.query(criteria), ApReadBehavior.class);
        if (apReadBehavior != null){
            apReadBehavior.setCount(apReadBehavior.getCount()+1);
            apReadBehavior.setUpdatedTime(new Date());
            apReadBehavior.setReadDuration(dto.getReadDuration());
            mongoTemplate.save(apReadBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //2.3.2 保存关注数据到数据库
        ApReadBehavior readBehavior = new ApReadBehavior();
        readBehavior.setUserId(user.getId().longValue());
        readBehavior.setEquipmentId(dto.getEquipmentId());
        readBehavior.setArticleId(dto.getArticleId());
        readBehavior.setCount(1);
        readBehavior.setReadDuration(dto.getReadDuration());
        readBehavior.setPercentage(dto.getPercentage());
        readBehavior.setLoadDuration(dto.getLoadDuration());
        readBehavior.setCreatedTime(new Date());
        readBehavior.setUpdatedTime(new Date());

        mongoTemplate.insert(readBehavior);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
